package com.hazy.animalface.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hazy.animalface.App;
import com.hazy.animalface.BaseActivity;
import com.hazy.animalface.R;
import com.hazy.animalface.adapter.StickersAdapter;
import com.hazy.animalface.event.RefreshStickerListEvent;
import com.hazy.animalface.module.Sticker;
import com.hazy.animalface.module.StickerBag;
import com.hazy.animalface.presenter.ILoadPresenter;
import com.hazy.animalface.presenter.ILoadPresenterCompl;
import com.hazy.animalface.utils.Base64Util;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;


/**
 * Created by Jiaui on 2017/4/21 0021.
 * <p/>
 * 一个头贴包的所有头贴
 */
public class StickersActivity extends BaseActivity implements ILoadView {

    public static final String STICKER_NAME_KEY = "name";
    public static final String STICKER_CONTROL_TYPE_KEY = "is_download";

    @Bind(R.id.toolbar)                         // 标题栏
            Toolbar mToolbar;
    @Bind(R.id.stickers_list)                   // 头贴详情
            RecyclerView mStickersList;
    @Bind(R.id.pay_to_download_btn)            // 下载按钮
            TextView mPayToDownloadView;

    private TextView mProgressTextView;
    private AlertDialog progressDialog;

    private ILoadPresenter iLoadPresenter;
    private StickersAdapter mStickersAdapter;
    private List<Sticker> stickerList;
    private Bitmap mBitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stickers);

        // 设置工具栏
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        // 设置标题
        final StickerBag stickerBag = (StickerBag) getIntent().getSerializableExtra(STICKER_NAME_KEY);
        if (stickerBag != null) {
            getSupportActionBar().setTitle(stickerBag.getName());
            iLoadPresenter = new ILoadPresenterCompl(this);
            iLoadPresenter.loadSticiersByName(stickerBag.getName());
        }

        // 是否下载
        boolean isDownload = getIntent().getBooleanExtra(STICKER_CONTROL_TYPE_KEY, false);
        if (isDownload) {
            mPayToDownloadView.setVisibility(View.VISIBLE);
            // 前往付款 下载
            mPayToDownloadView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    downloadFile();
                    if (stickerBag != null) {
                        if (Double.valueOf(stickerBag.getPrice()) == 0) {
                            String stickerName = Base64Util.encode(stickerBag.getName().getBytes());
                            String path = Environment.getExternalStorageDirectory() + "/Animal/" + stickerName;
                            File mHazyFile = new File(path);
                            try {
                                if (!mHazyFile.exists()) mHazyFile.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mSaveMessage = "下载成功";
                            messageHandler.sendMessage(messageHandler.obtainMessage());
                            EventBus.getDefault().post(new RefreshStickerListEvent());
                        } else {
                            // 支付
                        }
                    }
                }
            });
        }

        stickerList = new ArrayList<>();
        mStickersAdapter = new StickersAdapter(this, stickerList);
        mStickersList.setLayoutManager(new GridLayoutManager(this, 3));
        mStickersList.setAdapter(mStickersAdapter);

        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_upload_progress, null);
        mProgressTextView = (TextView) dialogView.findViewById(R.id.uploading_count_tv);
        mProgressTextView.setText(getString(R.string.loading));
        progressDialog = new AlertDialog.Builder(this).setView(dialogView).create();
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(false);

    }

    private void downloadFile() {
        if (stickerList != null) {
            for (int i = 0; i < stickerList.size(); i++) {
                final Sticker sticker = stickerList.get(i);
                String path = App.createHazy(sticker.getParentname());
                if (sticker != null) {
                    final File stickerFile = new File(path, sticker.getName());
                    try {
                        if (!stickerFile.exists()) stickerFile.createNewFile();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    URL url = new URL(sticker.getSticker().getUrl());
                                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                                    conn.setConnectTimeout(5 * 1000);
                                    conn.setRequestMethod("GET");
                                    InputStream inStream = conn.getInputStream();

                                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                                    byte[] buffer = new byte[1024];
                                    int len = 0;
                                    while ((len = inStream.read(buffer)) != -1) {
                                        outStream.write(buffer, 0, len);
                                    }
                                    outStream.close();
                                    inStream.close();

                                    byte[] data = outStream.toByteArray();
                                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
                                    saveFile(mBitmap, stickerFile);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param file
     * @throws IOException
     */
    public void saveFile(Bitmap bm, File file) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(StickersActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show();
        }
    };

    private String mSaveMessage;

    private class SaveFileRunnable implements Runnable {

        private Bitmap mBitmap;
        private File mFile;

        public SaveFileRunnable(Bitmap mBitmap, File mFile) {
            this.mBitmap = mBitmap;
            this.mFile = mFile;
        }

        @Override
        public void run() {
            try {
                saveFile(mBitmap, mFile);
                mSaveMessage = "图片保存成功！";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败！";
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
    }

    /**
     * 启动显示当前页
     *
     * @param context
     * @param stickerBag
     * @param isDownload 是否下载行为
     */
    public static void actionStart(Context context, StickerBag stickerBag, boolean isDownload) {
        Intent intent = new Intent(context, StickersActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(StickersActivity.STICKER_NAME_KEY, stickerBag);
        intent.putExtra(StickersActivity.STICKER_CONTROL_TYPE_KEY, isDownload);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public void onLoadResult(List<StickerBag> stickerBags) {

    }

    @Override
    public void onLoadSrickerDetail(boolean result, List<Sticker> stickers) {

        if (stickers != null) {
            ArrayList stickersUrlList = new ArrayList();
            for (Sticker sticker : stickers) {
                stickersUrlList.add(sticker.getSticker().getUrl());
            }
            mStickersAdapter.setStickersUrlList(stickersUrlList);
            stickerList.addAll(stickers);
            mStickersAdapter.notifyDataSetChanged();
        }
        progressDialog.dismiss();
    }

    @Override
    public void onCreateResult(boolean result, String message) {

    }

    @Override
    public void onUploadResult(boolean result, int progress, String message) {

    }
}
